package com.sdust.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sdust.common.constant.MessageConstant;
import com.sdust.common.properties.WeChatProperties;
import com.sdust.common.utils.HttpClientUtil;
import com.sdust.model.exceptions.LoginFailedException;
import com.sdust.model.user.dtos.UserLoginDto;
import com.sdust.model.user.entity.User;
import com.sdust.model.user.vos.WxLoginGetVo;
import com.sdust.user.mapper.UserMapper;
import com.sdust.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private HttpClientUtil httpClientUtil;

    /**
     * 测试查询用户
     * @param userName
     * @return
     */
    @Override
    public User testUser(String userName) {
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName, userName));
        return user;
    }

    /**
     * 微信登录
     * @param dto
     * @return
     */
    @Override
    public User wxLogin(UserLoginDto dto) {
        System.out.println("code:"+dto.getCode());

        //调用微信接口，获取用户openid
        String openid = getOpenId(dto.getCode());
        System.out.println("openid:"+openid);

        //判断openid是否空
        if(openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //判断当前用户是否为新用户（是否查询到了用户）
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getOpenid, openid));

        //如果是新用户，自动注册
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .lastLoginTime(LocalDateTime.now())
                    .userName("微信用户")
                    .build();
            userMapper.insert(user);
        }

        //返回用户对象
        return user;
    }

    /**
     * 获取微信用户openid
     * @param code
     * @return
     */
    private String getOpenId(String code) {

        //构建wx接口请求参数
        Map<String, String> map = new HashMap<>();

        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        System.out.println( map);

        String wxLoginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + weChatProperties.getAppid() + "&secret=" + weChatProperties.getSecret() + "&js_code=" + code + "&grant_type=authorization_code";
        WxLoginGetVo vo = httpClientUtil.doGet(wxLoginUrl, map);

        if(vo == null || vo.getOpenid() == null) {
            System.out.println(vo);
        }

        String openid = vo.getOpenid();

        return openid;
    }
}
